package org.edith.shiro.config;

import org.edith.shiro.component.ShiroRealm;
import org.edith.shiro.component.ShiroSessionManager;
import org.edith.shiro.constant.SHA256Constant;
import org.edith.shiro.filter.ShiroLoginFilter;
import org.edith.shiro.need.implement.UrlFilterInterface;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro配置类
 */
@Configuration
public class ShiroConfig {
    @Autowired(required = false)
    private UrlFilterInterface urlFilterInterface;

    @Autowired
    @Qualifier("edithRedisSessionDAO")
    private RedisSessionDAO redisSessionDAO;

    @Autowired
    @Qualifier("edithRedisCacheManager")
    private RedisCacheManager redisCacheManager;

    @Autowired
    @Qualifier("edithShiroRealm")
    private ShiroRealm shiroRealm;

    @Autowired
    @Qualifier("edithShiroSessionManager")
    private ShiroSessionManager shiroSessionManager;

    /**
     * 安全管理器
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 自定义session管理
        shiroSessionManager.setSessionDAO(redisSessionDAO);
        securityManager.setSessionManager(shiroSessionManager);
        // 自定义Cache实现
        securityManager.setCacheManager(redisCacheManager);
        // 自定义Realm验证
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        securityManager.setRealm(shiroRealm);
        return securityManager;
    }

    /**
     * 开启Shiro-aop注解支持,使用代理方式所以需要开启代码支持
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * Shiro基础配置
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        if(urlFilterInterface == null){
            Map<String, String> filterChainDefinitionMap = shiroFilterFactoryBean.getFilterChainDefinitionMap();
            Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();
            if(CollectionUtils.isEmpty(filterChainDefinitionMap) ||CollectionUtils.isEmpty(filters) ){
                throw new RuntimeException("请配置shiro过滤器");
            }
        }else{
            Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
            Map<String,Filter> filterMap = shiroFilterFactoryBean.getFilters();
            // 配置过滤:不会被拦截的链接
            if(!CollectionUtils.isEmpty(urlFilterInterface.getAnonUrlSet())){
                urlFilterInterface.getAnonUrlSet().forEach(url->filterChainDefinitionMap.put(url,"anon"));
            }
            if(!CollectionUtils.isEmpty(urlFilterInterface.getAnonFilters())) {
                urlFilterInterface.getAnonFilters().forEach(filter -> filterMap.put("anon", filter));
            }

            // 配置需要认证的URL
            if(!CollectionUtils.isEmpty(urlFilterInterface.getAuthcUrlSet())){
                urlFilterInterface.getAuthcUrlSet().forEach(url->filterChainDefinitionMap.put(url,"authc"));
            }
            if(!CollectionUtils.isEmpty(urlFilterInterface.getAuthcFilters())){
                urlFilterInterface.getAuthcFilters().forEach(filter->filterMap.put("authc",filter));
            }else{
                filterMap.put("authc",new ShiroLoginFilter() );
            }
            shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        }
        return shiroFilterFactoryBean;
    }


    /**
     * 凭证匹配器
     * 将密码校验交给Shiro的SimpleAuthenticationInfo进行处理,在这里做匹配配置
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        shaCredentialsMatcher.setHashAlgorithmName(SHA256Constant.HASH_ALGORITHM_NAME);
        shaCredentialsMatcher.setHashIterations(SHA256Constant.HASH_ITERATIONS);
        return shaCredentialsMatcher;
    }
}